var MY_ORG_STRUCT = (function() {
	
	function buildOneLevelOrg(orgStruct, level) { // DtInvsOrganizationStructureEntity.java
		var e = '';
		e += '<ul class="nav">';
			var isLeaf = true;
			if (orgStruct.childrens && orgStruct.childrens.length) isLeaf = false;
			e += '<li';
				e += ' data-orgid="' + orgStruct.id + '"';
				e += ' data-orgname="' + orgStruct.name + '"';
				e += ' data-level="' + level + '"'; // 第几级部门
				e += '>';
				e += '<a href="javascript:void(0);">';
					var i = level;
					while(--i > 0) {
						e += '<i class="placeholder"></i>';
					}
					if (!isLeaf) {
						e += '<i class="fa fa-caret-down openclose"></i>';// 有下级别部门时，显示 / 默认打开状态
					} else {
						e += '<i class="fa fa-caret-down openclose" style="visibility: hidden;"></i>';
					}
					e += '<span class="orgName">' + orgStruct.name + '</span>';
				e += '</a>';
			e += '</li>';
			if (!isLeaf) {
				$(orgStruct.childrens).each(function(idx, children) {
					e += buildOneLevelOrg(children, level + 1);
				});
			}
		e += '</ul>';
		return e;
	}
	
	function init() {
		$.ajax({
	        type: "POST", 
	        url: "wncrm_org_struct.do/org/load", 
	        dataType: "json",
	        data: {},
	        async: false,
	        success: function(orgStruct) {
	        	if (!WeKnow.filterAjaxResult(orgStruct)) return false; // session过期check
        		$('nav#orgStruct').append(buildOneLevelOrg(orgStruct, 1));
	        },
	        error: function() {
	        	WeKnow.systemMsg('系统异常');
	        }
		});
		
		// 显示根部门的成员
		$('nav#orgStruct li').first().click();
	}
	
	return {
		init: init,
		buildOneLevelOrg: buildOneLevelOrg
	}
})();


$(document).ready(function() {
	// 打开or收起 下级组织架构
	$('nav#orgStruct').on('click', 'li i.fa-caret-right, li i.fa-caret-down', function(event) {
		var $that = $(this);
		if ($that.hasClass('fa-caret-right')) { // 收起 to 打开
			$that.removeClass('fa-caret-right').addClass('fa-caret-down');
			$that.closest('li').nextAll('ul.nav').show();
		} else {// 打开 to 收起
			$that.removeClass('fa-caret-down').addClass('fa-caret-right');
			$that.closest('li').nextAll('ul.nav').hide();
		}
		event.stopPropagation();
	});
	
	// 组织架构
	$('nav#orgStruct').on('mouseover', 'li', function(event) {
	}).on('mouseout', 'li', function(event) {
	}).on('click', 'li', function(event) {
		var $that = $(this);
		
		// 员工list页面
		$('section#staff, section#guide-buy').hide(function() {
			$('section#org').show();
		});
		
		$('nav#orgStruct li').removeClass('active');
		$that.addClass('active');
		var orgId = $that.data('orgid');
		var orgName = $that.data('orgname');
		// 切换组织架构时，搜索内容删除
		$('section#org input[name="usersearch"]').val('');
		MY_STAFF.listStaff(orgId, orgName);
	});
	
	// 添加子部门名称
	$('section#org button[name="addSubOrg"]').on('click', function() {
		var $that = $(this);
		var $org = $that.closest('section#org');
		var orgId = $org.data('id');
		
		var $modal = $('#org-modal');
		$modal.modal({ keyboard: true })
		.on('shown.bs.modal', function() {
			$modal.find('h4.modal-title').text('新建部门');
			$modal.find('input[name="orgName"]').val('').focus();
			
			// 保存部门名称
			$modal.find('button[name="save"]').off('click').on('click', function() {
				var orgName = $.trim($modal.find('input[name="orgName"]').val());
				if (orgName && orgName.length) {
					
					$.ajax({
				        type: "POST", 
				        url: "wncrm_org_struct.do/org/add", 
				        dataType: "json",
				        data: {
				        	pOrgId: orgId,
				        	orgName: orgName
				        },
				        async: false,
				        success: function(data) {
				        	if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
				        	if (data.errorcode == 0) {
				        		$('#orgName').text(orgName);
				        		$('#orgStaffCnt').text(0);
				        		var $parentOrg = $('nav#orgStruct li[data-orgid="' + orgId + '"]');
				        		var $childrenOrg = $parentOrg.nextAll('ul.nav');
				        		if ($childrenOrg && $childrenOrg.length) {
				        			$childrenOrg.last().after(MY_ORG_STRUCT.buildOneLevelOrg(data.orgStruct, parseInt($parentOrg.data('level')) + 1));
				        		} else {
				        			$parentOrg.after(MY_ORG_STRUCT.buildOneLevelOrg(data.orgStruct, parseInt($parentOrg.data('level')) + 1));
				        		}
				        		// 显示【打开、收起】 标记
				        		$parentOrg.find('i.openclose').first().css('visibility', 'visible');
				        		$modal.modal('hide');
				        		WeKnow.successMsg('新建成功');
				        	} else {
				        		WeKnow.errorMsg('新建失败');
				        	}
				        },
				        error: function() {
				        	WeKnow.systemMsg('系统异常');
				        }
					});
				} else {
					WeKnow.errorMsg('请输入部门名称');
				}
			});
		}).on('hidden.bs.modal', function() {
			$modal.find('input[name="orgName"]').val('');
		});
	});
	
	// 修改部门名称
	$('section#org button[name="replaceOrgNm"]').on('click', function() {
		var $that = $(this);
		var $org = $that.closest('section#org');
		var orgId = $org.data('id');
		
		var $modal = $('#org-modal');
		$modal.modal({ keyboard: true })
		.on('shown.bs.modal', function() {
			$modal.find('h4.modal-title').text('修改部门名称');
			$modal.find('input[name="orgName"]').val($org.data('name')).focus();
			
			// 保存部门名称
			$modal.find('button[name="save"]').off('click').on('click', function() {
				var orgName = $.trim($modal.find('input[name="orgName"]').val());
				if (orgName && orgName.length) {
					
					$.ajax({
				        type: "POST", 
				        url: "wncrm_org_struct.do/org/rename", 
				        dataType: "json",
				        data: {
				        	orgId: orgId,
				        	orgName: orgName
				        },
				        async: false,
				        success: function(data) {
				        	if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
				        	if (data.errorcode == 0) {
				        		$('#orgName').text(orgName);
				        		$('nav#orgStruct li[data-orgid="' + orgId + '"]').data('orgname', orgName).find('a span.orgName').text(orgName).click();// click 用于刷新右边部门的名称
				        		$modal.modal('hide');
				        		WeKnow.successMsg('修改成功');
				        	} else {
				        		WeKnow.errorMsg('修改失败');
				        	}
				        },
				        error: function() {
				        	WeKnow.systemMsg('系统异常');
				        }
					});
				} else {
					WeKnow.errorMsg('请输入部门名称');
				}
			});
		}).on('hidden.bs.modal', function() {
			$modal.find('input[name="orgName"]').val('');
		});
	});
	
	// 删除部门名称
	$('section#org button[name="removeOrg"]').on('click', function() {
		var $that = $(this);
		var orgId = $that.closest('section#org').data('id');
		
		$.ajax({
	        type: "POST", 
	        url: "wncrm_org_struct.do/org/remove", 
	        dataType: "json",
	        data: {
	        	orgId: orgId
	        },
	        async: false,
	        success: function(data) {
	        	if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
	        	if (data.errorcode == 0) {
	        		var $orgLi = $('nav#orgStruct li[data-orgid="' + orgId + '"]');
	        		var $orgUl = $orgLi.parent('ul.nav');
	        		var $parentOrg = $orgUl.parent('ul.nav');
	        		$orgUl.remove(); // 删除自己以及自己的后代
	        		// 没有其他子部门时，隐藏【打开、收起】 标记
	        		if (!$parentOrg.find('ul.nav').length) {
	        			$parentOrg.find('i.openclose').css('visibility', 'hidden');
	        		}
	        		// 显示根部门的成员
	        		$('nav#orgStruct li').first().click();
	        		WeKnow.successMsg('删除成功');
	        	} else if (data.errorcode == 1) {
	        		WeKnow.errorMsg('该部门中存在成员, 无法删除');
	        	} else {
	        		WeKnow.successMsg('删除失败');
	        	}
	        },
	        error: function() {
	        	WeKnow.systemMsg('系统异常');
	        }
		});
	});
	
	// add by zhengxb 2018.4.9 start--------------------------------
	// 根据名字检索系统用户
	var autoSearch = null;
	$('section#org input[name="usersearch"]').on('input', function() {
		
		var $that = $(this);
		if (autoSearch) clearTimeout(autoSearch);
		autoSearch = setTimeout(function() {
			var $org = $that.closest('section#org');
			var orgId = $org.data('id');
			// 获取用户输入值
			var searchKeyName = $that.val();
			MY_STAFF.listStaffByName(orgId,searchKeyName );
			
			if (!$('section#org table tbody tr').length) {
				WeKnow.notifyMsg('没有找到员工');
			}
		}, 300);
		

	});
	// add by zhengxb 2018.4.9 start--------------------------------
	
	MY_ORG_STRUCT.init();
});